package problems.daily;

import java.util.HashMap;
import java.util.Map;

/**
 * 1797. 设计一个验证系统
 * <p>https://leetcode.cn/problems/design-authentication-manager/</p>
 *
 * @author habitplus
 * @since 2023/2/9 19:55
 */
public class DT1797 {
    class AuthenticationManager {
        private final int DURATION;
        // 也可以直接用 Map<String,Integer> codeTimeMap;
        private Map<Long, Integer> codeTimeMap;
        public AuthenticationManager(int timeToLive) {
            DURATION = timeToLive;
            codeTimeMap = new HashMap<>();
        }

        public void generate(String tokenId, int currentTime) {
            codeTimeMap.put(key(tokenId), currentTime + DURATION);
        }

        public void renew(String tokenId, int currentTime) {
            long k = key(tokenId);
            int time = codeTimeMap.getOrDefault(k, -1);
            if (time > 0 && time > currentTime) {
                codeTimeMap.put(k, currentTime + DURATION);
            }
        }

        public int countUnexpiredTokens(int currentTime) {
            int cnt = 0;
            for (Map.Entry<Long, Integer> e : codeTimeMap.entrySet()) {
                if (e.getValue() > currentTime) {
                    ++cnt;
                }
            }
            return cnt;
        }

        private long key(String token) {
            long ret = 0;
            long p = 1;
            for (char c : token.toCharArray()) {
                ret += p * (c - 'a' + 1);
                p *= 100;
            }
            return ret;
        }
    }
}
